package com.zr.rabbitmq.consumer;

import com.rabbitmq.client.Channel;
import com.zr.rabbitmq.config.RabbitMQConfirmConfig;
import com.zr.rabbitmq.dto.MessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.LinkOption;

/**
 * 邮件消息消费者
 */
@Slf4j
@Component
public class EmailConsumer implements CommandLineRunner {

    @Value("${rabbitmq.queue.email}")
    private String emailQueue;

    @Autowired
    ApplicationContext applicationContext;

    /**
     * 监听邮件队列，处理邮件消息
     */
    @RabbitListener(queues = "${rabbitmq.queue.email}",containerFactory = "rabbitListenerContainerFactory")
    public void handleEmailMessage(MessageDTO message, Channel channel, Message amqpMessage) throws IOException {
        log.info("接收到邮件消息，队列: {}, 消息内容: {}", emailQueue, message);
        try {
            // 处理邮件消息的业务逻辑
            processEmailMessage(message);
            
            // 手动确认消息已消费
            channel.basicAck(amqpMessage.getMessageProperties().getDeliveryTag(), false);
            log.info("邮件消息处理成功，消息ID: {}", message.getId());
        } catch (Exception e) {
            log.error("邮件消息处理失败，消息ID: {}", message.getId(), e);
            
            // 处理失败，拒绝消息并将其重新放入队列
            channel.basicNack(
                    amqpMessage.getMessageProperties().getDeliveryTag(), 
                    false, 
                    true  // 是否重新入队
            );
        }
    }
    
    /**
     * 处理邮件消息的业务逻辑
     */
    private void processEmailMessage(MessageDTO message) {
        // 这里是处理邮件发送的实际业务逻辑
        // 例如调用邮件服务发送邮件
        log.info("正在向 {} 发送邮件: {}", message.getRecipient(), message.getContent());
    }

    @Override
    public void run(String... args) throws Exception {
        Object rabbitListenerContainerFactory = applicationContext.getBean("rabbitListenerContainerFactory");
        log.info("rabbitListenerContainerFactory: {}", rabbitListenerContainerFactory);
    }
}
